/**
 * 路径拼接
 *
 * @param {string} basePath 基础路径
 * @param {string} path 后续路径
 * @returns 完整路径
 */
const pathJoin = (basePath, path) => {
  if (basePath === '/' || basePath === '') {
    return basePath + path;
  }
  return basePath + '/' + path;
};

/**
 * 过滤路由表
 *   过滤出以 root 开始的路由项
 *
 * @param {array<RouteRecord>} routes 路由表
 * @returns
 */
const filterRoutes = (routes) => {
  return routes.filter((route) => route.meta.isRoot);
};

/**
 * 生成侧边菜单（递归）
 *
 * @param {*} routes 路由表
 * @returns {array} 菜单列表
 */
const generateMenusRecur = (routes) => {
  const result = [];

  routes.forEach((route) => {
    if (!route?.meta?.isMenu && route?.children?.length < 1) {
      return;
    }

    let currRoute;
    if (route?.meta?.isMenu) {
      currRoute = {
        ...route,

        path: route.path,
        children: [],
      };
      result.push(currRoute);
    }

    if (route?.children?.length) {
      if (currRoute) {
        currRoute.children.push(...generateMenusRecur(route.children));
      } else {
        result.push(...generateMenusRecur(route.children));
      }
    }
  });

  return result;
};

/**
 * 生成侧边菜单
 *
 * @param {array<RouteRecord>} routes 路由表
 * @returns
 */
const generateMenus = (routes) => {
  return generateMenusRecur(filterRoutes(routes));
};

/**
 * 生成可搜索的路由对象（递归）
 *
 * @param {array<RouteRecord>} routes 路由表
 * @param {string} prefixTitle 前缀标题
 * @returns {array} 搜索列表
 */
const generateRoutesForSearchRecur = (routes, prefixTitle = []) => {
  const res = [];

  for (const route of routes) {
    let title = route.meta.title ? [route.meta.title] : [];

    if (route.meta.canSearched) {
      title = [...prefixTitle, ...title];
      const data = {
        path: route.path,
        title,
      };

      res.push(data);
    }

    if (route.children && route.children.length) {
      const children = generateRoutesForSearchRecur(route.children, title);
      if (children.length) {
        res.push(...children);
      }
    }
  }

  return res;
};

/**
 * 生成可搜索的路由对象
 *
 * @param {array<RouteRecord>} routes 路由表
 * @returns
 */
function generateRoutesForSearch(routes) {
  return generateRoutesForSearchRecur(filterRoutes(routes));
}

export { generateMenus, generateRoutesForSearch };
